package org.springblade.wechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.gson.JsonElement;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.util.json.WxMpTemplateMessageGsonAdapter;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.tool.api.R;
import org.springblade.wechat.entity.MyWxMpTemplateData;
import org.springblade.wechat.entity.MyWxMpTemplateMessage;
import org.springblade.wechat.mapper.MpMapper;
import org.springblade.wechat.service.IMpService;
import org.springblade.wechat.util.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * @author LK
 * @version 1.0.0
 * @Title: MpServiceImpl.java
 * @Description: TODO    微信公众号服务类
 * @date 2020/4/7 14:54
 */
@Service
@AllArgsConstructor
public class MpServiceImpl implements IMpService {

	private static Logger logger = LoggerFactory.getLogger(IMpService.class);

	MpMapper mpMapper;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	/**
	 * 发送微信公众号模板消息
	 *
	 * @param myWxMpTemplateMessageListStr
	 * @return
	 */
	@Override
	public R<HashMap<String, Object>> sendWxMpTemplateMessage(String myWxMpTemplateMessageListStr, String xxlx) {
		JSONArray jsonArray = JSON.parseArray(myWxMpTemplateMessageListStr);
		List<MyWxMpTemplateMessage> myWxMpTemplateMessageList;
		myWxMpTemplateMessageList = jsonArray.toJavaList(MyWxMpTemplateMessage.class);
		HashMap result = new HashMap();
		//获取通行令牌
		String accessToken = redisTemplate.boundValueOps("access_token").get();
		System.out.println("access_token为：" + accessToken);
		String OPENID = "";
		WxMpTemplateMessageGsonAdapter WxMpTemplateMessageGsonAdapter;
		WxMpTemplateMessage wxMpTemplateMessage;
		if (!StringUtils.isEmpty(accessToken)) {
			for (MyWxMpTemplateMessage myWxMpTemplateMessage : myWxMpTemplateMessageList) {
				WxMpTemplateMessageGsonAdapter = new WxMpTemplateMessageGsonAdapter();
				wxMpTemplateMessage = WxMpTemplateMessage.builder().build();
				//设置发送用户
				if (myWxMpTemplateMessage.getToUser() != null && !myWxMpTemplateMessage.getToUser().isEmpty()) {
					wxMpTemplateMessage.setToUser(myWxMpTemplateMessage.getToUser());
				} else {
					wxMpTemplateMessage.setToUser(OPENID);
				}
				//设置模板id
				if ("1".equals(xxlx)) {
					wxMpTemplateMessage.setTemplateId("M8euW_bOH2CzEjcl5Yx4WSMk3sU2O3xFnps-78fnX30");
				} else if ("2".equals(xxlx)) {
					wxMpTemplateMessage.setTemplateId("p6dQYUG9Ty7brfiE626PsVrCO86rp0RjqEuOP9camgE");
				} else {
					wxMpTemplateMessage.setTemplateId("6wVusw0OnZeDXIn_FYXdL8vm2yaAZhsmHk0Mld6ErB0");
				}
				if (myWxMpTemplateMessage.getUrl() != null && !myWxMpTemplateMessage.getUrl().isEmpty()) {
					wxMpTemplateMessage.setUrl(myWxMpTemplateMessage.getUrl());
				} else {
					//暂时百度
					wxMpTemplateMessage.setUrl("http://118.190.141.98:8199/#/login");
				}
				List<MyWxMpTemplateData> myWxMpTemplateData = myWxMpTemplateMessage.getData();
				if (myWxMpTemplateData != null && !myWxMpTemplateData.isEmpty()) {
					for (MyWxMpTemplateData myWxMpTemplateDatum : myWxMpTemplateData) {
						wxMpTemplateMessage.addData(new WxMpTemplateData(myWxMpTemplateDatum.getName(), myWxMpTemplateDatum.getValue(), myWxMpTemplateDatum.getColor()));
					}
				} else {
					result.put("Status", 200);
					result.put("msg", "发送数据为空");
					//暂时默认模板数据
					return R.data(result);
				}
				JsonElement jsonElement = WxMpTemplateMessageGsonAdapter.serialize(wxMpTemplateMessage, null, null);
				String wxMpTemplateMessageJsonStr = jsonElement.toString();
				String res = null;
				res = HttpClientUtil.doPostJson("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken, wxMpTemplateMessageJsonStr);
				logger.info("响应信息ifgo======" + res);
				result.put("Status", 200);
				result.put("msg", "公众号服务模板消息发送成功，公众号平台回馈信息为：" + res);
			}
		} else {
			logger.info("获取redis缓存中的通行令牌为空");
			result.put("Status", 401);
			result.put("msg", "通行令牌获取为null");
		}
		return R.data(result);
	}

	/**
	 * 根据微信公众号id和用户id获取openId
	 *
	 * @param mpId
	 * @param userId
	 * @return
	 */
	@Override
	public R<String> getOpenIdByMpIdAndUserId(String mpId, String userId) {
		return R.data(mpMapper.getOpenIdByMpIdAndUserId(mpId, userId));
	}
}
